#include "../include/WebPageSearcher.hpp"
#include "../include/WebPageQuery.hpp"

#include <nlohmann/json.hpp>
#include <unistd.h>
using Json = nlohmann::json;
using std::to_string;

/* WebPageSearcher::WebPageSearcher(string keys, const TcpConnectionPtr & conn) */
/* :ProtocolParser(keys) */
/* , _conn(conn) */
/* , _sought(keys) */
/* ,_redis() */
/* { */
/*     _redis.connect("127.0.0.1",6379); */
/*     //协议解析类会把网页查询任务分给这个类去做 */
/* } */

WebPageSearcher::WebPageSearcher()
    :_redis()
{
    cout << "WebPageSearcher :" <<_sought << endl;
    _redis.connect("127.0.0.1",6379);
    //协议解析类会把网页查询任务分给这个类去做
}
void WebPageSearcher::doQuery(const string sought)
{
    _result.clear();
    _sought = sought;
    vector<string> titleUrls;//存储第二个key
    bool flag =_redis.getKeys(_sought,titleUrls);//默认先去Redis缓存系统找,一堆网页
    if(flag)
    {

        cout << "_redis query " << endl;
        for(size_t i = 0;i < 10 && i < titleUrls.size();++i)
        { 
            string values = _redis.getValues(_sought,titleUrls[i]);
            cout << _sought << titleUrls[i] << values << endl;
            _result.push_back(titleUrls[i] + "\n" + values + "\n");
        }
    }
    else
    {
        cout << "disk query" << endl;
        WebPageQuery wbq;
        wbq.loadLibrary();

        Json root;
        root = Json::parse(wbq.doQuery(_sought));
        int N = root.size();

        cout << endl << endl << endl;
        for(int idx = 1; idx <= N && idx<10; ++idx){
            /* cout << root[to_string(idx)]["title"].get<string>() << endl; */
            /* cout << root[to_string(idx)]["url"].get<string>() << endl; */
            /* cout << root[to_string(idx)]["summary"].get<string>() << endl; */

            string title =  root[to_string(idx)]["title"].get<string>() ;
            string url   =  root[to_string(idx)]["url"].get<string>();
            string summary = root[to_string(idx)]["summary"].get<string>() ;

            _result.push_back(title + "\n" + url + "\n" + summary + "\n");
            cout << _sought << title << url <<summary << endl;
            //将网页信息加入容器
            _redis.set(_sought,title + "\n"+url,summary);
        }
    }

    //发送给客户端

    //将allWords解析

    //重新将该信息加入容器
    _redis.setOutTime(_sought);//设置该键值的过期时间
    /* _redis.setOutTime(_sought);//设置该键值的过期时间 */

} 

vector<string> WebPageSearcher::getResult(){
    return _result;
}


